<template>
 
<div class="todo-container">
    <div class="todo-wrap">
     <Header :addTodo="addTodo" />
     <List :todos="todos"
      :deleteTodo:"deleteTodo" 
      :updateTodo:"updateTodo"
      />
     <Footer :todos="todos" 
     :checkAll="checkAll"
     :clearAllCompletedTodos="clearAllCompletedTodos"
     />
      
      
    </div>
  </div>
  </template>

<script lang="ts">
    import {
        defineComponent,
        reactive,
        toRefs,watch,onMounted
    } from 'vue'
    //引入直接的子级组件
    import Header from './components/Header.vue'
    import List from './components/List.vue'

    import Footer from './components/Footer.vue'
    //定义一个接口 约束state的数据类型  引入这个接口
    import {
        Todo
    } from './types/todo'
import {saveTodos,readTodos} from './utils/localStorageUtils'
    export default defineComponent({
        name: 'App',
        components: {
            Header,
            List,
            Footer
        },
        //数据应该用数组来存储 数组中的每个数据都是一个对象 对象中应该有三个属性（id ,title,isCompleted）
        //把数组攒钱定义中App.vue父级组件
        setup() {
             const state = reactive<{ todos: Todo[] }>({
    todos: [ ],
     })
     //界面加载完毕之后过了一会儿再读取数据
     onMounted(()=>{
         setTimeout(()=>{
state.todos=readTodos()
         },2000)
     })
     //添加删除数据的方法
     const deleteTodo=(index:number)=>{
         state.todos.splice(index,1)
     }
     //添加数据的方法
     const addTodo =(todo:Todo) =>{
       state.todos.unshift(todo)
     }
     //修改todo的isCompleted状态的方法
     const updateTodo=(todo:Todo,isCompleted:boolean)=>{
todo.isCompleted=isCompleted
     }
     //全选或者全不选的方法
     const checkAll=(isCompleted:boolean)=>{
         //比阿尼数组
         state.todos.forEach((todo)=>{
             todo.isCompleted=isCompleted
         })
     }

        // 清理所有选中的数据
    const clearAllCompletedTodos = () => {
      state.todos = state.todos.filter((todo) => !todo.isCompleted)
    }
    //监视操作：如果todos数组的数据变化率 直接存储到浏览器的缓存中
   // watch(()=>state.todos,(value)=>{
        //保存到浏览器的缓存中
      //  localStorage.setItem('todos_key',JSON.stringify(value))
   // },{deep:true})
    watch(()=>state.todos,(value)=>{
        //保存到浏览器的缓存中
    saveTodos(value)
    },{deep:true})
    //上面写的可以简写  
    // 
    
    watch(() => state.todos, saveTodos, { deep: true })
            return {
                //对state进行一个结构 让上面直接调用state
                ...toRefs(state),
                addTodo,
               deleteTodo,
               updateTodo,
               checkAll,
               clearAllCompletedTodos
            }
        }
    })
</script>

<style scoped>
    .todo-container {
        width: 600px;
        margin: 0 auto;
    }
    
    .todo-container .todo-wrap {
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 5px;
    }
</style>